<template>
  <!-- 门诊医生-处方 -->
  <div class="w-full h-full relative">
    <a-spin :spinning="thisStore.loading" class="w-full h-full mt-20">
      <template v-for="(tableItem, index) in thisStore.tableList" :key="tableItem.tableKey">
        <div class="flex justify-between items-center p-2 mt-2 table-header">
          <div class="flex items-center">
            <div class="font-bold w-10 mr-2">处方{{ index + 1 }}</div>
            <a-select
              v-model:value="tableItem.medicineType"
              class="w-[72px]"
              :options="[
                { label: '普', value: '0' },
                { label: '精一', value: '1' },
                { label: '精二', value: '2' },
                { label: '麻醉', value: '3' }
              ]"
            />
            <!-- 药房 -->
            <SelectDrugRoom
              :value="tableItem.drugStoreName"
              :params="{ storetype: 1, isLocalStore: 0 }"
              select-first
              class="w-52 ml-2"
              :disabled="!!tableItem.dataSource[0]?.cfbh"
              @select="onChangeDrugRoom($event, tableItem)"
            />
            <span class="ml-2 flex-center">
              显示已作废医嘱
              <a-switch v-model:checked="thisStore.switchList[tableItem.cfbh]" class="mx-2" @click="thisStore.getData(cfbh, $event)" />
            </span>
          </div>

          <a-space>
            <a-button ghost type="primary" @click="onOpenTemplate(tableItem.tableKey)">处方套餐</a-button>
            <a-button>注射输液单</a-button>
            <!-- <a-button v-print="{ id: 'printMe' }">打印处方</a-button>
            <div class="absolute top-[-9999px] hidden">
              <PrintView id="printMe" />
            </div> -->
            <a-button @click="onPrintConfirm(tableItem)">打印处方</a-button>
            <BaseButton :confirm-text="`确认删除处方${index + 1}？`" :icon="h(DeleteOutlined)" danger size="small" @click="thisStore.deleteTable(tableItem)" />
          </a-space>
        </div>
        <!-- 处方表格 -->
        <TableItem :ref="(e) => getRef(e, tableItem.tableKey)" :table-key="tableItem.tableKey" :table-index="index" />
      </template>
      <!-- 处方模板 -->
    </a-spin>
    <TemplateModal v-model:open="templateModalOpen" @success="onAddTemplate" />
    <a-card class="sticky bottom-0 z-30">
      <a-space class="flex justify-end -mr-2">
        <a-button @click="thisStore.addTable()">新增处方</a-button>
        <a-button type="primary" :disabled="thisStore.isHaveNewRow" @click="saveSign()">签署 </a-button>
      </a-space>
    </a-card>
    <div class="absolute top-[-9999px] hidden">
      <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
      <PrintView id="printMe" :print-data="printData" />
    </div>
  </div>
</template>
<script setup>
import { ref, h, onMounted, createVNode } from 'vue'
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { post } from '@/utils/request'
import cofirmModal from '@/utils/confirm'
import userInfo from '../../store'
import useStore from './store'
import TemplateModal from './TemplateModal'
import PrintView from './PrintView'
import TableItem from './TableItem'

const thisStore = useStore()
const thisUserStore = userInfo()
const templateModalOpen = ref(false)
const tableItemRef = ref({})
const currentTableKey = ref()
const tableListId = ref([])
const onOpenTemplate = (tableKey) => {
  thisStore.tableKey = tableKey
  currentTableKey.value = tableKey
  templateModalOpen.value = true
}
const printMe = ref(null)
const printData = ref('')
const getRef = (e, tableKey) => {
  tableItemRef.value[tableKey] = e
}
const onAddTemplate = async (list) => {
  const isAddSucceed = await thisStore.addTemplate(currentTableKey.value, list)
  isAddSucceed && (templateModalOpen.value = false)
  tableItemRef.value[currentTableKey.value].onCalcTotal()
}
const onPrintConfirm = (current) => {
  const flag = current.dataSource.some((item) => {
    return !item.isNew && item.yzzt === 0
  })
  if (flag) {
    Modal.confirm({
      title: '提示',
      centered: true,
      icon: createVNode(ExclamationCircleOutlined),
      content: '当前还存在未签署的医嘱，是否继续打印？',
      okText: '继续',
      cancelText: '取消',
      onOk() {
        onPrint(current)
      },
      onCancel() {
        return
      }
    })
  } else {
    onPrint(current)
  }
}
const onPrint = async (current) => {
  const { code, msg, data } = await post('/outp/outPrint/getMedicinePrescriptionPrint', { cfbh: current.cfbh, jzbh: thisUserStore.currentPatient.jzbh })
  if (code !== 0) return message.error(msg)

  const isArmy = getSystemConfig('NAVYHIS_MODE') === '1'
  if (isArmy) {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printMe.value.$el.click()
    }, 500)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}

const onChangeDrugRoom = async (select, table) => {
  table.drugStoreId = select.id
  table.drugStoreName = select.storeName
}

// 签署
const saveSign = async () => {
  // skinTestFlag = 1 皮试
  const skinList = []
  thisStore.tableList.forEach((i) => {
    if (i?.dataSource.length > 0) {
      i.dataSource.forEach((j) => {
        if (j?.sfxm?.skinTestFlag === 1) {
          skinList.push(j)
        }
      })
    }
  })
  tableListId.value = thisStore.tableList.map((i) => getListId(i.dataSource)).flat()
  if (tableListId.value[0] === '') {
    return message.error('不能为空')
  }
  if (skinList.length > 0) {
    const isConfirm = await cofirmModal({ title: '提示', content: '有需要皮试的项目，是否立即签署？' })
    if (isConfirm) {
      const { code, msg } = await post('/outp/mzys/signedDoctor', {
        yzid: tableListId.value,
        chekSkinSign: 0,
        brId: thisUserStore.currentPatient.brId,
        yzzt: 1
      })
      if (code !== 0) return message.error(msg || '签署失败')
      message.success(msg)
      await thisStore.getData()
    }
  } else {
    const { code, msg } = await post('/outp/mzys/signedDoctor', {
      yzid: tableListId.value,
      yzzt: 1
    })
    if (code !== 0) return message.error(msg || '签署失败')
    message.success(msg)
    await thisStore.getData()
  }
}

// 获取所有医嘱id
const getListId = (children) => {
  return children.reduce((ids, child) => {
    // if (child.allowSign) {
    //   //如果是需皮试的药，判断是否可以签署
    //   ids.push(child.id)
    // }
    ids.push(child.id)
    if (child.children) {
      ids = ids.concat(getListId(child.children))
    }
    return ids
  }, [])
}
// watch(
//   () => thisUserStore.clickInfo,
//   async (val) => {
//     if (val.bh && val.mc && (val.xmlb === 2 || val.xmlb === 4 || val.xmlb === 5)) {
//       thisStore.clickAddTable()
//     }
//   }
// )
onMounted(() => {
  thisStore.tableList = []
  thisStore.getData()
})
</script>
<style lang="less" scoped>
.table-header {
  background-color: var(--thin-color);
  border-radius: 2px;
  &:first-child {
    margin-top: 0;
    border: none;
  }
}
</style>
